package tech.yixiyun.framework.kuafu.boot;


import tech.yixiyun.framework.kuafu.kits.ClassKit;
import tech.yixiyun.framework.kuafu.log.LOGGER;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * 类扫描器，扫描项目里的所有非jre的类
 */
public class ClassScanner {

    /**
     * 扫描所有的classpath下的类，并返回类的全路径的集合
     * @return
     */
    public List<String> scan() {
        LOGGER.infoTitle("启动：扫描所有类");
        String[] paths = ClassKit.getJavaClassPaths();
        ArrayList<String> list = new ArrayList<>();

        for (String path : paths) {

            if (path.endsWith(".jar"))  {
                list.addAll(scanJarClasses(path));
            } else {
                LOGGER.debug("类扫描路径：" + path);
                list.addAll(ClassKit.scanLocalClasses(path, true));
            }

        }
        return list;
    }

    private List<String> scanJarClasses(String jarPath) {
        try {
            JarFile jar = new JarFile(new File(jarPath));
            Manifest manifest = null;
            manifest = jar.getManifest();
            //如果是其他jar包，判断manifest中有没有forwardModule:true，有了说明是项目依赖的业务模块，才会去解析加载
            if (manifest != null) {
                String value = (String) manifest.getMainAttributes().get(new Attributes.Name("forwardModule"));
                boolean isForwardModule = Objects.equals(value, "true");
                if (isForwardModule) {
                    LOGGER.debug("类扫描路径：" + jarPath);
                    return ClassKit.scanJarClasses(jar);
                }

            }
            return Collections.emptyList();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
